<?php defined('SYSPATH') or die('No direct access allowed.');
use Grafika\Grafika; // Import package
use Grafika\Color;
require_once BASEPATH . "/res/vendor/grafika-master/src/autoloader.php";
class Model_Fenxiao_Shareposter extends ORM
{
    // 字体路径
    private function get_font_path(){
        return BASEPATH."/data/mark/STXINWEI.TTF"; // （选填）字体的完整路径
    }

    /**
     * 默认标准海报模板 内容不固定
     * @param $savePath
     * @param array $params
     * @throws Exception
     */
    public static function standard_mould1($savePath,$params = array())
    {
        // 海报1的背景
        $bg = BASEPATH."/plugins/fenxiao/public/mobile/images/share/mudle_1_bg.jpg";
        $bgWidth = 750;
        // 字体文件路径
        $font = self::get_font_path();
        // 海报数据 设定不显示时值为false
        $defaultConfig = array(
            'logo'=> array( // 分销商logo
                'path'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/logo.jpg',
            ),
            'title'=> array( // 产品标题
                'type'=> 'text',
                'text'=> '印度尼西亚巴厘岛+蓝梦岛7日5晚半自助游(5钻)·直飞纯玩惠·蓝梦出海+激情漂流 Villa+5星',
                'line'=> 3, // 显示的行数
                'width'=> 700, // 如果要处理行数就要设置显示宽度
                'size'=> 22,
                'dy'=> 748,
                'dx'=> 20,
                'color'=> "#333333",
                'angle'=> 0
            ),
            'sealPoint'=> array( // 卖点
                'type'=> 'text',
                'text'=> '5月23日引爆周三、蓝梦岛出海（水上活动一价全含无隐形消费）网红大瀑布等热门景点',
                'line'=> 2, // 显示的行数
                'width'=> 700, // 如果要处理行数就要设置显示宽度
                'size'=> 18,
                'dy'=> 748,
                'dx'=> 20,
                'color'=> "#666666",
                'angle'=> 0
            ),
            'useDate'=> array( // 使用时间
                'type'=> 'text',
                'text'=> '使用时间：2018-5-21，2018-5-22，2018-5-23，2018-5...',
                'line'=> 1, // 显示的行数
                'width'=> 700, // 如果要处理行数就要设置显示宽度
                'size'=> 16,
                'dy'=> 748,
                'dx'=> 20,
                'color'=> "#999999",
                'angle'=> 0
            ),
            'litpic'=> array( // 封面图
                'num'=> 1,
                'path'=> BASEPATH.'plugins/fenxiao/public/mobile/images/share/banner.jpg',
            ),
            'piclist'=> array( // 产品图片
                'num'=> 2,
                'path'=> array(
                    BASEPATH.'/plugins/fenxiao/public/mobile/images/share/banner.jpg',
                    BASEPATH.'/plugins/fenxiao/public/mobile/images/share/banner.jpg',
                    BASEPATH.'/plugins/fenxiao/public/mobile/images/share/banner.jpg',
                ),
            ),
            'tips'=> array( // 备注
                'type'=> 'text',
                'text'=> '备注：本产品由北京途牛国际旅行社有限公司成都分公司及具有资 质的合作旅行社提供相关服务',
                'line'=> 5, // 显示的行数
                'width'=> 700, // 如果要处理行数就要设置显示宽度
                'size'=> 18,
                'dy'=> 748,
                'dx'=> 20,
                'color'=> "#666666",
                'angle'=> 0
            ),
            'distribution'=> array( // 分销数据
                'codeImg'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/fe771f52671c38a3ab18fabaf170bd7e.png',//分销产品二维码
                'username'=> '用户名示例',
                'face'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/face.png',//头像
                'account'=> '13548085398',//邮箱或者手机号
            ),
            'price'=> array( // 价格
                'type'=> 'text',
                'text'=> '0.00'
            )
        );

        // 合并数据
        foreach ($defaultConfig as $dk=> &$dv){
            if(isset($params[$dk]))
            {
                $dv = $params[$dk] ? array_merge($dv,$params[$dk]) : false;
            }
            else
            {
                $dv = false;
            }
        }

        $height = 25; // 页面初始高度
        $editor = Grafika::createEditor();
        $editor->open($bgImg,$bg);

        // 封面图片
        if(isset($defaultConfig['litpic']) && $defaultConfig['litpic'])
        {
            $bgImg = self::img_to_standard1($defaultConfig['litpic'],$bgWidth,$height,$bgImg);
            $height += 10;
        }


        // 产品标题
        if(isset($defaultConfig['title']) && $defaultConfig['title'])
        {
            $bgImg = self::text_to_standard1($defaultConfig['title'],$bgWidth,$height,$font,$bgImg);
            $height += 10;
        }

        // 卖点
        if(isset($defaultConfig['sealPoint']) && $defaultConfig['sealPoint'])
        {
            $bgImg = self::text_to_standard1($defaultConfig['sealPoint'],$bgWidth,$height,$font,$bgImg);
            $height += 10;
        }

        // 使用时间
        if(isset($defaultConfig['useDate']) && $defaultConfig['useDate'])
        {
            $bgImg = self::text_to_standard1($defaultConfig['useDate'],$bgWidth,$height,$font,$bgImg);
            $height += 10;
        }

        // 价格
        if(isset($defaultConfig['price']) && $defaultConfig['price'])
        {
            $ph = $height;
            $bgImg = self::add_img_height($bgImg,$height,44);

            $editor->text($bgImg ,'￥',16,25,($ph + 10),new Color("#ff7700"),$font,0);
            $editor->text($bgImg ,$defaultConfig['price']['text'],26,45,$ph,new Color("#ff7700"),$font,0);
            $price_box = imagettfbbox(26,0,$font,$defaultConfig['price']['text']);
            $price_width = $price_box[2];
            $editor->text($bgImg ,'起',16,($price_width + 50),($ph + 10),new Color("#ff7700"),$font,0);
            $height+=10;
        }

        // 说明信息
        if(isset($defaultConfig['tips']) && $defaultConfig['tips'])
        {
            $bgImg = self::text_to_standard1($defaultConfig['tips'],$bgWidth,$height,$font,$bgImg);
            $height += 10;
        }


        // logo
        if(isset($defaultConfig['logo']) && $defaultConfig['logo'])
        {
            $defaultConfig['logo']=['num'=>1,'path'=> $defaultConfig['logo']['path']];
            $bgImg = self::img_to_standard1($defaultConfig['logo'],$bgWidth,$height,$bgImg);
            $height += 10;
        }


        // 产品图片
//        if(isset($defaultConfig['piclist']) && $defaultConfig['piclist'])
//        {
//            $piclist = array_chunk($defaultConfig['piclist']['path'],2);
//            foreach ($piclist as $k=> $v)
//            {
//                if($k == 0)
//                {
//                    $picArr = array(
//                        'num'=> 2,
//                        'path'=> $v
//                    );
//                    $bgImg = self::img_to_standard1($picArr,$bgWidth,$height,$bgImg);
//                    $height += 10;
//                }
//                else
//                {
//                    foreach ($v as $cv){
//                        $picArr = array(
//                            'num'=> 1,
//                            'path'=> $cv
//                        );
//                        $bgImg = self::img_to_standard1($picArr,$bgWidth,$height,$bgImg);
//                        $height += 10;
//                    }
//                }
//            }
//        }

        //开启了分销商信息
        if(isset($defaultConfig['distribution']) && $defaultConfig['distribution']['username']!='用户名示例')
        {
            $distribution = $defaultConfig['distribution'];
            $bgImg = self::add_img_height($bgImg,$height,250);
            // 设置分销商背景
            $dh = $height - 250;
            $drawingObject = Grafika::createDrawingObject('Rectangle', $bgWidth, 250, array(0, $dh), 0 , new Color('#2dbb55'), new Color('#2dbb55'));
            $editor->draw( $bgImg, $drawingObject);
            // 用户名
            $editor->text($bgImg ,$distribution['username'],18,48,($dh + 147),new Color("#ffffff"),$font,0);
            $editor->text($bgImg ,$distribution['account'],18,48,($dh + 190),new Color("#ffffff"),$font,0);

            // 处理头像
            $editor->open($faceImg,$distribution['face']);
            $editor->resizeFill($faceImg , 90, 90);
            $editor->corners($faceImg);
            $editor->blend($bgImg, $faceImg , 'normal', 1 , 'top-left',48,($dh + 34));

            // 底部二维码
            $editor->open( $codeImg,$distribution['codeImg']);
            $editor->resizeExactWidth($codeImg , 160);
            $editor->blend($bgImg, $codeImg , 'normal', 1 , 'top-left',540,($dh + 34));

            $editor->text($bgImg ,'扫码了解更多产品',16,536,($dh + 205),new Color("#ffffff"),$font,0);
            $height += 10;
        }else{
            $distribution = $defaultConfig['distribution'];
            $bgImg = self::add_img_height($bgImg,$height,250);
            // 设置分销商背景
            $dh = $height - 250;
            $drawingObject = Grafika::createDrawingObject('Rectangle', $bgWidth, 250, array(0, $dh), 0 , new Color('#2dbb55'), new Color('#2dbb55'));
            $editor->draw( $bgImg, $drawingObject);
            // 底部二维码
            $editor->open( $codeImg,$distribution['codeImg']);
            $editor->resizeExactWidth($codeImg , 160);
            $editor->blend($bgImg, $codeImg , 'normal', 1 , 'top-left',540,($dh + 34));
            $editor->text($bgImg ,'扫码了解更多产品',16,536,($dh + 205),new Color("#ffffff"),$font,0);
            $height += 10;
        }

        $editor->save($bgImg , $savePath);
    }

    // 添加图片高度
    public function add_img_height($baseImg,&$startHeight,$addHeight,$bgWidth = 750)
    {
        $bg = BASEPATH."/plugins/fenxiao/public/mobile/images/share/mudle_1_bg.jpg";
        $editor = Grafika::createEditor();
        $editor->open($bgImg,$bg);
        $allHeight = $startHeight + $addHeight;
        $editor->resizeExact($bgImg ,$bgWidth,$allHeight);
        $editor->blend($bgImg, $baseImg , 'normal', 1 , 'top-left',0,0);
        $startHeight = $allHeight;
        return $bgImg;
    }

    /**
     * 将文字生成到标准海报上
     * @param $textData
     * @param $bgWidth
     * @param $startHeight
     * @param $font
     * @param $baseImg
     * @return array
     */
    public function text_to_standard1($textData,$bgWidth,&$startHeight,$font,$baseImg)
    {
        $bg = BASEPATH."/plugins/fenxiao/public/mobile/images/share/mudle_1_bg.jpg";

        $fontBox = imagettfbbox($textData['size'], 0, $font, '高度测试'); // 测试文字高度
        $allHeight = $startHeight;
        if(isset($textData['line']))
        { // 根据要显示的行数处理文字显示
            $textArr = self::get_text_image_box($textData['text'],$textData['size'],$font,$textData['width']);

            foreach ($textArr as $k=> $v)
            {
                if($k < $textData['line'])
                {
                    // 计算文字高度
                    $allHeight = intval($allHeight) + abs(intval($fontBox[5])) + abs(intval($fontBox[5]))/2; // 下一行高度

                }
            }
        }
        else
        {
            // 计算文字高度
            $allHeight = intval($allHeight) + abs(intval($fontBox[5])) + abs(intval($fontBox[5]))/2; // 下一行高度

        }

        $editor = Grafika::createEditor();
        // 将文字生成到图片上
        $editor->open($bgImg,$bg);
        $editor->resizeExact($bgImg ,$bgWidth,$allHeight);

        if(isset($textData['line']))
        { // 根据要显示的行数处理文字显示
            $textArr = self::get_text_image_box($textData['text'],$textData['size'],$font,$textData['width']);

            foreach ($textArr as $k=> $v)
            {
                if($k < $textData['line'])
                {
                    // 计算文字高度
                    $editor->text($bgImg ,$v,$textData['size'],$textData['dx'],$startHeight,new Color($textData['color']),$font,$textData['angle']);
                    $startHeight = intval($startHeight) + abs(intval($fontBox[5])) + abs(intval($fontBox[5]))/2; // 下一行高度
                }
            }
        }
        else
        {
            $editor->text($bgImg ,$textData['text'] ,$textData['size'],$textData['dx'],$startHeight,new Color($textData['color']),$font,$textData['angle']);
            // 计算文字高度
            $allHeight = intval($allHeight) + abs(intval($fontBox[5])) + abs(intval($fontBox[5]))/2; // 下一行高度
        }

        if($baseImg)
        {
            // 合并图片
            $editor->blend($bgImg, $baseImg , 'normal', 1 , 'top-left',0,0);
        }
        $startHeight = $allHeight;
        return $bgImg;
    }

    /**
     * @function 将图片生成到标准海报上
     * @param $imgData
     * @param $bgWidth
     * @param $startHeight
     * @param $baseImg
     * @return mixed
     */
    public function img_to_standard1($imgData,$bgWidth,&$startHeight,$baseImg)
    {
        $num = $imgData['num']; // 每行显示的数量 目前支持1张和两张
        $path = $imgData['path'];
        $bg = BASEPATH."/plugins/fenxiao/public/mobile/images/share/mudle_1_bg.jpg";

        $editor = Grafika::createEditor();
        $allHeight = $startHeight;

        if($num == 1)
        {
            $editor->open($bgImg,$bg);
            $editor->open($newImg,$path);
            $editor->resizeExactWidth($newImg,700);
            $imgHeight = $newImg->getHeight();
            $allHeight = $allHeight + $imgHeight;
            $editor->resizeExact($bgImg ,$bgWidth, $allHeight);
            $editor->blend($bgImg, $newImg, 'normal', 1 , 'top-left',25,$startHeight);
            $startHeight = $allHeight+10;
        }
        else if($num == 2)
        {
            $editor->open($bgImg,$bg);
            $allHeight = $allHeight + 230;
            $editor->resizeExact($bgImg ,$bgWidth, $allHeight);
            if($path[0]) {
                $editor->open($newImg1, $path[0]);
                $editor->resizeFill($newImg1,340,230);
                $editor->blend($bgImg, $newImg1, 'normal', 1 , 'bottom-left',25,0);
            }
            if($path[1])
            {
                $editor->open($newImg2,$path[1]);
                $editor->resizeFill($newImg2,340,230);
                $editor->blend($bgImg, $newImg2, 'normal', 1 , 'bottom-right',-25,0);
            }
            $startHeight = $allHeight+10;
        }

        if($bgImg && $baseImg)
        {
            // 合并图片
            $editor->blend($bgImg, $baseImg , 'normal', 1 , 'top-left',0,0);
        }

        return $bgImg ? $bgImg : $baseImg;
    }


    /**
     * 标准海报 模板一
     * @param $savePath
     * @param array $params
     * @return array
     */
    public static function standard_mould2($savePath,$params = array())
    {
        // 海报基础配置
        $defaultConfig = array(
            'bg' => array(
                'type'=> 'img',
                'path'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/mudle_2.jpg',
            ),
            'priceBg' => array(
                'type'=> 'img',
                'path'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/mudle_2_price.png',
                'dy'=> 646,
                'dx'=> 28,
            ),
            'priceStart' => array(
                'type'=> 'img',
                'path'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/price_start.png',
                'dy'=> 648,
                'dx'=> 500,
            ),
            'priceSymbol' => array(
                'type'=> 'img',
                'path'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/price_symbol.png',
                'dy'=> 648,
                'dx'=> 28,
            ),
            'banner'=> array( // 背景 必填
                'type'=> 'img',
                'path'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/banner.jpg',
                'dy'=> 20,
                'dx'=> 28,
            ),
            'face'=> array( // 头像 必填
                'type'=> 'img',
                'path'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/face.png',
                'dy'=> 950,
                'dx'=> 238,
            ),
            'codeImg'=> array( // 二维码 必填
                'type'=> 'img',
                'path'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/fe771f52671c38a3ab18fabaf170bd7e.png',
                'dy'=> 1023
            ),
            'price'=>array( // 价格 必填
                'type'=> 'text',
                'text'=> '300.00',
                'size'=> 22,
                'dy'=> 674,
                'dx'=> 60,
                'color'=> "#FFFFFF",
                'angle'=> 0
            ),
            'title'=>array( // 标题 必填
                'type'=> 'text',
                'text'=> '标题示例',
                'line'=> 2, // 显示的行数
                'width'=> 670, // 如果要处理行数就要设置显示宽度
                'size'=> 22,
                'dy'=> 736,
                'dx'=> 20,
                'color'=> "#333333",
                'angle'=> 0
            ),
            'date'=>array( // 使用时间 必填
                'type'=> 'text',
                'text'=> '使用时间：使用时间示例',
                'line'=> 1,  // 显示的行数
                'width'=> 650,// 如果要处理行数就要设置显示宽度
                'size'=> 18,
                'dy'=> 825,
                'dx'=> 30,
                'color'=> "#2dbb55",
                'angle'=> 0
            ),
            'sellpoint'=>array( // 卖点
                'type'=> 'text',
                'text'=> '卖点示例',
                'line'=> 2, // 显示的行数
                'width'=> 650, // 如果要处理行数就要设置显示宽度
                'size'=> 18,
                'dy'=> 880,
                'dx'=> 20,
                'color'=> "#666666",
                'angle'=> 0
            ),
            'username'=>array( // 用户名 必填
                'type'=> 'text',
                'text'=> '用户名示例',
                'size'=> 18,
                'dy'=> 970,
                'dx'=> 348,
                'color'=> "#333333",
                'angle'=> 0
            ),
            'account'=>array( // 账号
                'type'=> 'text',
                'text'=> '135*******98',
                'size'=> 18,
                'dy'=> 1010,
                'dx'=> 348,
                'color'=> "#333333",
                'angle'=> 0
            ),
            'footerText'   =>  array(
                'type'=> 'text',
                'text'=> '扫码了解更多产品',
                'size'=> 16,
                'dy'=> 1320,
                'dx'=> 'center',
                'color'=> "#FFFFFF",
                'angle'=> 0
            ),
        );

        // 合并数据
        foreach ($defaultConfig as $dk=> &$dv){
            if(isset($params[$dk]))
            {
                $dv = array_merge($dv,$params[$dk]);
            }
        }

        // 字体文件路径
        $font = self::get_font_path();
        try {
            // 创建图片
            $editor = Grafika::createEditor();
            $editor->open($image1,$defaultConfig['bg']['path']);
            // 获取图片宽高
            $bgWidth = $image1->getWidth();

            // 处理头像
            $face = $defaultConfig['face'];
            $editor->open($faceImg,$face['path']);
            $editor->resizeFill($faceImg , 90, 90);
            $editor->corners($faceImg);
            $editor->blend($image1, $faceImg , 'normal', 1 , 'top-left',$face['dx'],$face['dy']);

            // 处理banner图
            $banner = $defaultConfig['banner'];
            $editor->open($bannerImg,$banner['path']);
            $editor->resizeFill($bannerImg , 696, 696);
            $editor->radius($bannerImg , 10);
            $editor->blend($image1, $bannerImg , 'normal', 1 , 'top-left',$banner['dx'],$banner['dy']);

            // 处理价格背景图
            $priceSymbol = $defaultConfig['priceSymbol'];
            $editor->open($priceSymboltImg,$priceSymbol['path']);
            $editor->blend($image1, $priceSymboltImg , 'normal', 1 , 'top-left',$priceSymbol['dx'],$priceSymbol['dy']);

            // 绘制价格矩形背景
            $price = $defaultConfig['price'];
            $price_box = imagettfbbox($price['size'],0,$font,$price['text']);
            $price_width = $price_box[2] + 8;
            $drawingObject = Grafika::createDrawingObject('Rectangle', $price_width, 69, array(60, 648), 0 , new Color('#ff4f00'), new Color('#ff4f00'));
            $editor->draw( $image1, $drawingObject );
            $start_dx = 60+ $price_width;
            $priceStart = $defaultConfig['priceStart'];
            $editor->open($priceStartImg,$priceStart['path']);
            $editor->blend($image1, $priceStartImg , 'normal', 1 , 'top-left',$start_dx,$priceStart['dy']);

            // 循环处理文字类型数据
            foreach ($defaultConfig as $k_text => &$v_text)
            {
                if($v_text['type'] == 'text')
                {
                    if($v_text['dx'] == 'center')
                    {
                        $v_text['dx'] = self::get_text_center_dx($v_text['text'],$v_text['size'],$bgWidth,$font);
                    }
                    // 标题
                    if(isset($v_text['line']))
                    { // 根据要显示的行数处理文字显示
                        $textArr = self::get_text_image_box($v_text['text'],$v_text['size'],$font,$v_text['width']);
                        $textDy = $v_text['dy'];
                        foreach ($textArr as $k=> $v)
                        {
                            if($k < $v_text['line'])
                            {
                                // 计算文字高度
                                $editor->text($image1 ,$v,$v_text['size'],$v_text['dx'],$textDy,new Color($v_text['color']),$font,$v_text['angle']);
                                $fontBox = imagettfbbox($v_text['size'], 0, $font, $v);
                                $textDy = intval($textDy) + abs(intval($fontBox[5])) + abs(intval($fontBox[5]))/2; // 下一行高度
                            }
                        }
                    }
                    else
                    {
                        $editor->text($image1 ,$v_text['text'],$v_text['size'],$v_text['dx'],$v_text['dy'],new Color($v_text['color']),$font,$v_text['angle']);
                    }
                }
            }

            // 底部二维码
            $editor->open( $image2,$defaultConfig['codeImg']['path']);
            $editor->resizeExactWidth($image2 , 160);
            $editor->blend($image1, $image2 , 'normal', 1 , 'bottom-center',0,-178);
            // 保存图片
            $editor->save($image1 , $savePath);
            return array(
                'status'=> true,
                'msg'=> ''
            );
        }
        catch (Exception $e) {
            return array(
                'status'=> false,
                'msg'=> $e
            );
        }
    }


    /**
     * 高级海报
     * @param string $savePath  保存路径
     * @param array $params 定位相关参数
     * @return array
     */
    public static function best_poster($savePath,$params = array())
    {
        $defaultConfig = array(
            'bg' => array(
                'path'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/banner_4.jpg',
            ),
            'codeImg'=> array(
                'path'=> '',
                'position'=> 'bottom-right',
                'dx'=>'-10',
                'dy'=>'-10',
            )
        );

        foreach ($defaultConfig as $dk=> &$dv){
            if(isset($params[$dk]))
            {
                $dv = array_merge($dv,$params[$dk]);
            }
        }
        try {
            // 创建图片
            $editor = Grafika::createEditor();
            $editor->open( $image1,$defaultConfig['bg']['path']);
            $codeImg = $defaultConfig['codeImg'];
            $editor->open( $image2,$codeImg['path']);
            $editor->resizeExactWidth($image2 , 200);
            $editor->blend ( $image1, $image2 , 'normal', 1, $codeImg['position'], $codeImg['dx'], $codeImg['dy']);

            $editor->save($image1 , $savePath);
            return array(
                'status'=> true,
                'msg'=> ''
            );
        }
        catch (Exception $e) {
            return array(
                'status'=> false,
                'msg'=> $e
            );
        }
    }

    /**
     * @function
     * @param $savePath
     * @param array $params
     * @return array
     */
    public static function distribution_invite_poster($savePath,$params = array())
    {
        // 海报基础配置
        $defaultConfig = array(
            'bg' => array(
                'path'=>BASEPATH.'/plugins/fenxiao/public/mobile/images/share/banner_4.jpg',
            ),
            'face'=> array(
                'path'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/face.png',
                'dy'=> 143
            ),
            'codeImg'=> array(
                'path'=> BASEPATH.'/plugins/fenxiao/public/mobile/images/share/fe771f52671c38a3ab18fabaf170bd7e.png',
                'dy'=> 1023
            ),
            'username'=>array(
                'text'=> '用户名示例',
                'size'=> 18,
                'dy'=> 264,
                'color'=> "#FFFFFF",
                'angle'=> 0
            ),
            'inviteText'   =>  array(
                'text'=> '用户名示例邀请您，一起赚取海量佣金',
                'size'=> 22,
                'dy'=> 756,
                'color'=> "#000000",
                'angle'=> 4
            ),
            'footerText'   =>  array(
                'text'=> '— 长按识别二维码 加入—',
                'size'=> 20,
                'dy'=> 1340,
                'color'=> "#000000",
                'angle'=> 0
            ),
        );

        // 合并数据
        foreach ($defaultConfig as $dk=> &$dv){
            if(isset($params[$dk]))
            {
                $dv = array_merge($dv,$params[$dk]);
            }
        }

        // 字体文件路径
        $font = self::get_font_path();
        try {
            // 创建图片
            $editor = Grafika::createEditor();
            $editor->open($image1,$defaultConfig['bg']['path']);
            // 获取图片宽高
            $bgWidth = $image1->getWidth();
            // 绘制头像圆形背景
            $drawingObject = Grafika::createDrawingObject('Ellipse', 100, 100, array(325, 138), 0 , new Color('#FFFFFF'), new Color('#FFFFFF'));
            $editor->draw( $image1, $drawingObject );
            // 处理头像
            $face = $defaultConfig['face'];
            $editor->open($faceImg,$face['path']);
            $editor->resizeFill($faceImg , 90, 90);
            $editor->corners($faceImg);
            $editor->blend($image1, $faceImg , 'normal', 1 , 'top-center',0,$face['dy']);
            // 用户名
            $username = $defaultConfig['username'];
            $dx1 = self::get_text_center_dx($username['text'],$username['size'],$bgWidth,$font);
            $editor->text($image1 ,$username['text'],$username['size'],$dx1,$username['dy'],new Color($username['color']),$font,$username['angle']);
            // 邀请文字
            $inviteText = $defaultConfig['inviteText'];
            $dx2 = self::get_text_center_dx($inviteText['text'],$inviteText['size'],$bgWidth,$font);
            $editor->text($image1 ,$inviteText['text'],$inviteText['size'],$dx2,$inviteText['dy'],new Color($inviteText['color']),$font,$inviteText['angle']);
            // 底部文字
            $footerText = $defaultConfig['footerText'];
            $dx3 = self::get_text_center_dx($footerText['text'],$footerText['size'],$bgWidth,$font);
            $editor->text($image1 ,$footerText['text'],$footerText['size'],$dx3,$footerText['dy'],new Color($footerText['color']),$font,$footerText['angle']);

            // 底部二维码
            $editor->open( $image2,$defaultConfig['codeImg']['path']);
            $editor->resizeExactWidth($image2 , 240);
            $editor->blend($image1, $image2 , 'normal', 1 , 'top-center',0,1050);

            // 保存图片
            $editor->save($image1 , $savePath);

            return array(
                'status'=> true,
                'msg'=> ''
            );
        }
        catch (Exception $e) {
            return array(
                'status'=> false,
                'msg'=> $e
            );
        }
    }

    /**
     * 获取文字在图片上的居中偏移值
     * @param string $str  字符串
     * @param int $size  字符大小
     * @param int $width  所在位置的总宽度
     * @param string $font  字体文件路径
     * @return float
     */
    public function get_text_center_dx($str,$size,$width,$font)
    {
        // 获取文字位置
        $tb = imagettfbbox($size,0,$font,$str);
        return ceil(($width - $tb[2]) / 2);
    }

    /**
     * 根据设定的宽度获取一行或多行的文字数组
     * @param string $str
     * @param int $fontSize
     * @param string $font // 字体文件路径
     * @param int $boxWidth
     * @return array
     */
    public function get_text_image_box($str,$fontSize,$font,$boxWidth)
    {
        // 将字符串拆分成一个个单字 保存到数组 letter 中
        $letter = array();
        for ($i=0;$i<mb_strlen($str);$i++)
        {
            $letter[] = mb_substr($str, $i, 1);
        }

        $res = array(); // 文字数组
        $content = '';
        foreach ($letter as $l) {
            $testStr = $content." ".$l;
            $fontBox = imagettfbbox($fontSize, 0, $font, $testStr);
            // 判断拼接后的字符串是否超过预设的宽度
            if (($fontBox[2] > $boxWidth) && ($content !== "")) {
                array_push($res,$content);
                $content = '';
            }
            else
            {
                $content .= $l;
            }
        }
        // 如果不满一行
        if($content){
            array_push($res,$content);
        }
        return $res;
    }

    /**
     * @function 获取价格团期
     * @param $productid
     * @param $typeid
     * @return string
     */
    public static function get_product_price_date($productid,$typeid)
    {
        $limit = 4;
        $now_time = time();
        if($typeid == 1)
        { // 线路
            $price_table = 'sline_line_suit_price';
            $id_name = 'lineid';
        }
        else if($typeid == 2)
        { // 酒店
            $price_table = 'sline_hotel_room_price';
            $id_name = 'hotelid';
        }
        else if($typeid == 3)
        { // 租车
            $price_table = 'sline_car_suit_price';
            $id_name = 'carid';
        }
        else if($typeid == 5)
        { // 景点
            $price_table = 'sline_spot_ticket_price';
            $id_name = 'spotid';
        }
        else if($typeid == 13)
        { // 团购
            $price_table = 'sline_tuan_price';
            $id_name = 'tuan_id';
        }
        else if($typeid == 104)
        { // 邮轮
            $price_table = 'sline_ship_line_suit_price';
            $id_name = 'lineid';
        }
        else if($typeid == 114)
        { // 户外
            $price_table = 'sline_outdoor_suit_price';
            $id_name = 'outdoorid';
        }

        if($price_table && $id_name)
        {
            $sql = "SELECT `day` FROM {$price_table} WHERE `day`>{$now_time} AND `{$id_name}`={$productid} GROUP BY `day` ORDER BY `day` ASC LIMIT {$limit} ";
            $list = DB::query(1,$sql)->execute()->as_array();
            if(!empty($list))
            {
                $str = '使用时间：';
                $date_arr = array();
                foreach ($list as $v)
                {
                    array_push($date_arr,date('Y-m-d',$v['day']));
                }

                $dateStr = implode('、',$date_arr);
                $str .=$dateStr.'......';
                return $str;
            }
        }

        return '';
    }

    /**
     * @function
     * @param $fxurl
     * @param $pid
     * @param $userid
     * @param $comefrom
     * @return array
     */
    public static function get_product_code($fxurl,$pid,$userid,$comefrom,$url)
    {
        //获得分销信息
        $fenxiao = DB::select()->from('fenxiao')->where('memberid', '=', $userid)->execute()->current();
        $fenxiao['fxrank_name'] = Model_Fenxiao_Rank::get_name($fenxiao['fxrankid']);
        if($comefrom == 'h5')
        {
            $path     = '/uploads/uniapp/productCode/h5/' . date('Y') . '/';
            $filename = md5($fenxiao['fxcode'] . $fxurl . $pid);
//            $fxurl   = str_replace('//','/','/'.$fxurl);
//            $fxurl   = $GLOBALS['cfg_m_main_url'].$fxurl.'.html?fxpcode='.$fenxiao['fxcode'];
//            $fxurl   = self::reorganized_resource_url($fxurl);
            $imgPath  = self::get_code_url($url, $path, $filename);

            return array('status'=> true, 'msg'=> '', 'path'=> $imgPath);
        }
        else
        {
            return array('status'=> false, 'msg'=> '不支持该类型海报分销');
        }
    }

    /**
     * @function
     * @param $url
     * @param string $status
     * @return string
     */
    public static function reorganized_resource_url($url,$status='')
    {
        if(!empty($url))
        {
            $http = stripos(strtolower($url), 'http://') ;
            $https = stripos(strtolower($url), 'https://') ;
            if( $http === $https)
            {
                $url = $status=='logo'?$GLOBALS['cfg_basehost'] . $url:$GLOBALS['cfg_basehost'] .'/'. $url;
                return  $url;
            }
        }
        return $url;
    }

    /**
     * @param $share_url 二维码内容
     * @param $path 二维码存储路径
     * @param $filename 文件名
     * @param bool $logo 是否需要logo
     * @return bool|string
     */
    public static function get_code_url($share_url, $path, $filename, $logo = false)
    {
//        require_once BASEPATH . "/plugins/api/vendor/qrcode/phpqrcode.php";
        require_once BASEPATH . "/res/vendor/qrcode/phpqrcode.php";
        $errorCorrectionLevel = "Q";
        $matrixPointSize = 4;
        $img_url = $path.$filename.'.png';
        QRcode::png($share_url, BASEPATH.$img_url, $errorCorrectionLevel, $matrixPointSize);

        return $img_url;
    }

    /**
     * @function base64 图片保存并返回路径
     * @param $base64_image_content
     * @param $path string 保存文件路径
     * @param string $filename 不传使用时间戳作为文件名
     * @return bool|string
     */
    public static function base64_image_content($base64_image_content,$path,$filename = '')
    {
        //匹配出图片的格式
        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content, $result)){

            // 图片后缀
            $type = $result[2];
            // 根目录
            $dir  = rtrim(BASEPATH . '/', '\\../');
            // 存放文件夹
            $new_file = $dir;
            // 循环查询文件是否存在
            $fileArr = explode('/',$path);
            foreach ($fileArr as $fileV)
            {
                if($fileV)
                {
                    $new_file .= '/'.$fileV;
                    if(!file_exists($new_file)){
                        //检查是否有该文件夹，如果没有就创建
                        mkdir($new_file, 0777);
                    }
                }
            }

            // 图片名
            $filename = $filename ? $filename : time().rand('100000','999999');
            $img = $filename.".{$type}";

            $new_filename = $new_file.'/'.$img; // 文件存放位置
            $resUrl = $path.$img; // 保存成功后返回全路径
            // 检查文件是否存在
            if(file_exists($new_filename)){
                //检查是否有该文件夹，如果没有就创建
                return $resUrl;
            }

            // 保存文件
            if (file_put_contents($new_filename, base64_decode(str_replace($result[1], '', $base64_image_content))))
            {
                return $resUrl;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return false;
        }
    }
}